package org.inspiration.dudu.web.controller.message;

import lombok.RequiredArgsConstructor;
import org.inspiration.dudu.message.model.dto.MessageDTO;
import org.inspiration.dudu.message.model.entity.MessageEntity;
import org.inspiration.dudu.message.model.entity.SessionEntity;
import org.inspiration.dudu.message.service.MessageService;
import org.inspiration.dudu.message.service.SessionService;
import org.inspiration.dudu.web.annotation.Loggable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;

@Controller
@RequiredArgsConstructor
@Loggable
public class ChatController {
    private final MessageService messageService;
    private final SessionService sessionService;
    private final SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/private-chat")
    @Transactional
    public void sendPrivateMessage(MessageDTO messageDTO) {
        Long senderId = messageDTO.getSenderId();
        Long receiverId = messageDTO.getReceiverId();

        //确保对话创建过
        SessionEntity sessionEntity = sessionService.getSession(senderId, receiverId);

        //保存消息
        MessageEntity messageEntity = messageService.transToEntity(messageDTO);
        messageService.save(messageEntity);
        //添加对话中未读消息数量
        sessionService.increaseUnreadCount(sessionEntity.getSessionId());
        // 发送消息
        messagingTemplate.convertAndSendToUser(receiverId.toString(), "/queue/messages", messageService.transToVO(messageEntity));
    }

}
